import { Injectable } from '@angular/core'
import { HttpClient, HttpResponse, HttpErrorResponse } from '@angular/common/http'
import { Observable, throwError } from 'rxjs'
import { catchError, map } from 'rxjs/operators'
import { JWTTokenModel } from '@delon/auth'

import { COMB_URL } from 'app/utils/contraints'
import { User, ILoginForm } from '@shared/interfaces/user'
@Injectable({
  providedIn: 'root',
})
export class LoginService {
  constructor(
    private http: HttpClient,
  ) {}

  login(data: ILoginForm): Observable<JWTTokenModel> {
    const url = `${COMB_URL}/auth/login`
    return this.http
      .post<User>(url, data, { observe: 'response' }) // ---resp body
      .pipe(
        map(resp => this.handleLogin(resp)), // --- jwtTokenModel
        catchError(err => this.handleError(err)), // --- throwError #
      )
  }

  private handleLogin(resp: HttpResponse<User>): JWTTokenModel {
    const user = resp.body
    const token = resp.headers.get('access_token')
    const model = new JWTTokenModel()
    model.token = token
    model['user'] = user
    return model
  }

  private handleError(err: HttpErrorResponse) {
    return throwError(err)
  }
}
